package stock;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import net.sf.json.JSONArray;
import stock.model.SuanFaModel;
import stock.model.SuanFaModel2;
@Component
@SuppressWarnings("all")
public class SunFa3 implements SunFa3Interface {
	@SuppressWarnings("unused")
	@Autowired
	private ProjectSession projectSession;

	@PersistenceContext
	private EntityManager entityManager;

	@Resource
	private JdbcTemplate jdbcTemplate;

	/**
	 * 得到分歧的的地方
	 */
	@Override
	public void jisuan1(String flag) {
		// TODO Auto-generated method stub
		System.out.println("计算分歧股票sunfa3");
		// TODO Auto-generated method stub
		Session session = ContextUtil.getSessionFactory1().openSession();
		List<StockGaiNian> list = session.createQuery("from StockGaiNian t where t.shizhi <= ?0 and t.shizhi>=?1 ")
				.setParameter(0, 400f).setParameter(1, 50f).list();
		int numThreads = 20;
		int chunkSize = list.size() / numThreads;
		ExecutorService executor = Executors.newFixedThreadPool(numThreads);
		for (int i = 0; i < numThreads; i++) {
			final int start = i * chunkSize;
			final int end = (i == numThreads - 1) ? list.size() : (i + 1) * chunkSize;
			executor.execute(() -> aaa(list.subList(start, end), flag));
			System.out.println("开启一个线程" + i);
		}
		executor.shutdown();
	}

	public static boolean validateList(List<Float> list) {
		boolean isFirstElementValid = list.get(0) >= 0;
		int countNegativeElements = 0;

		for (int i = 1; i < list.size(); i++) {
			if (list.get(i) < 0) {
				countNegativeElements++;
				if (countNegativeElements > 1) {
					return false;
				}
			}
		}

		return isFirstElementValid;
	}

	private static void aaa(List<StockGaiNian> chunk, String flag) {

		String sql1 = "select t.zhandifu from stock t where t.code = ?0  order by t.date desc limit 0,5 "; // 40天以内价格距离最小值
		String sql2 = "select t.huanshoulv from stock t where t.code = ?0  order by t.date desc  limit 0,5"; // 5天内成交量总和
		String sql3 = "select  count(*) from stock t where t.code = ?0  and t.zhandifu >=4  and t.date > ?1 "; // 大于4
		String sql4 = "select  count(*) from stock t where t.code = ?0  and t.zhandifu <=-4  and t.date > ?1 "; // 小于-4
		String sql5 = " from SuanFaModel2 t where t.code1 = ?0  and t.createTime = ?1 ";
		LocalDate currentDate = LocalDate.now();
		Integer date120DaysAgo = Integer.parseInt(currentDate.minusDays(120).toString().replace("-", ""));
		Session session = ContextUtil.getSessionFactory1().openSession();

		String codeall = "";

		for (int i = 0; i < chunk.size(); i++) {

			String temp1 = "";
			if (chunk.get(i).getCode().indexOf("6") == 0) {
				temp1 = "sh" + chunk.get(i).getCode();
			} else {
				temp1 = "sz" + chunk.get(i).getCode();
			}
			if (i == chunk.size() - 1) {
				codeall += temp1;
			} else {
				codeall += temp1 + ",";
			}
		}
		JSONArray josnar = StockContrl.getCcc(codeall, -1000f);
		DecimalFormat df = new DecimalFormat("#.##");
		session.getTransaction().begin();
		for (Iterator<StockGaiNian> iterator = chunk.iterator(); iterator.hasNext();) {
			StockGaiNian stockGaiNian = iterator.next();
			List<Float> list1 = session.createSQLQuery(sql1).setParameter(0, stockGaiNian.getCode()).list();

			boolean b = validateListAllZhen(list1);

			if (b == false) {
				continue;
			}

			List<Float> list2 = session.createSQLQuery(sql2).setParameter(0, stockGaiNian.getCode()).list();
			String list3 = (String) session.createSQLQuery(sql3).setParameter(0, stockGaiNian.getCode())
					.setParameter(1, date120DaysAgo).uniqueResult().toString();
			String list4 = (String) session.createSQLQuery(sql4).setParameter(0, stockGaiNian.getCode())
					.setParameter(1, date120DaysAgo).uniqueResult().toString();
			SuanFaModel2 sm0 = (SuanFaModel2) session.createQuery(sql5).setParameter(0, stockGaiNian.getCode())
					.setParameter(1, DateTools.getCurrentDate("yyyyMMdd")).uniqueResult();
			String name = (String) session
					.createSQLQuery("select DISTINCT(name) from stock t where t.code = ?0 limit 0,1")
					.setParameter(0, stockGaiNian.getCode()).uniqueResult();
			float sum = 0.0f;
			for (Float num : list2) {
				if (num == null) {
					continue;
				}
				sum += num;
			}
			Float hsl = 0f;
			Float zdf = 0f;
			Float priceC = 0f;
			for (int i = 0; i < josnar.size(); i++) {
				if (stockGaiNian.getCode()
						.equals(josnar.getJSONObject(i).getString("code").replace("sh", "").replace("sz", ""))) {
					hsl = Float.valueOf((String) josnar.getJSONObject(i).get("huanshoulv"));
					zdf = Float.valueOf((String) josnar.getJSONObject(i).get("zhangdiefu"));
					priceC = Float.valueOf((String) josnar.getJSONObject(i).get("jiage"));
					break;
				}
			}
			if (sm0 == null) {
				SuanFaModel2 sm = new SuanFaModel2();
				sm.setCode1(stockGaiNian.getCode());
				sm.setCreateTime(DateTools.getCurrentDate("yyyyMMdd"));
				sm.setDie5(list4 + "");
				sm.setZhang5(list3 + "");
				sm.setName1(name);
				sm.setGn1(stockGaiNian.getGn());
				sm.setJulizuixiao(df.format(calculateDifferenceRatio(list1)) + "");
				sm.setSumcjl5(df.format(sum) + "");
				sm.setDqhuanshoulv(hsl + "");
				sm.setDqzhangdifu(zdf + "");
				sm.setPrice1(priceC + "");
				sm.setJgbi(stockGaiNian.getJgbi() + "");
				sm.setJgcount(stockGaiNian.getJgcount() + "");
				sm.setHy(stockGaiNian.getHy());
				sm.setCp(stockGaiNian.getCp());
				sm.setQy(stockGaiNian.getQy());
				sm.setJlr(stockGaiNian.getJlr());
				sm.setYs(stockGaiNian.getYs());
				session.save(sm);
			} else {
				sm0.setCode1(stockGaiNian.getCode());
				sm0.setCreateTime(DateTools.getCurrentDate("yyyyMMdd"));
				sm0.setDie5(list4 + "");
				sm0.setZhang5(list3 + "");
				sm0.setName1(name);
				sm0.setGn1(stockGaiNian.getGn());
				sm0.setJulizuixiao(df.format(calculateDifferenceRatio(list1)) + "");
				sm0.setSumcjl5(df.format(sum) + "");
				sm0.setDqhuanshoulv(hsl + "");
				sm0.setDqzhangdifu(zdf + "");
				sm0.setPrice1(priceC + "");
				sm0.setJgbi(stockGaiNian.getJgbi() + "");
				sm0.setJgcount(stockGaiNian.getJgcount() + "");
				sm0.setHy(stockGaiNian.getHy());
				sm0.setCp(stockGaiNian.getCp());
				sm0.setQy(stockGaiNian.getQy());
				sm0.setJlr(stockGaiNian.getJlr());
				sm0.setYs(stockGaiNian.getYs());
				session.merge(sm0);
			}

		}
		session.getTransaction().commit();
		session.clear();
		session.close();

	}

	public static boolean validateListAllZhen(List<Float> list) {
		boolean isFirstElementValid = list.get(0) >= 0;
		for (int i = 1; i < list.size(); i++) {
			if (list.get(i) < 0) {
				return false;
			}
		}
		return isFirstElementValid;
	}

	public static float calculateDifferenceRatio(List<Float> numbers) {
		if (numbers == null || numbers.isEmpty()) {
			throw new IllegalArgumentException("List<Float> should not be null or empty.");
		}

		float firstNumber = numbers.get(0);
		float minNumber = numbers.get(0); // 初始化为第一个数

		for (float number : numbers) {
			if (number < minNumber) {
				minNumber = number;
			}
		}

		// float difference = Math.abs(firstNumber - minNumber);
		float ratio = ((firstNumber - minNumber) / firstNumber) * 100;

		return ratio;
	}

	@Override
	public JSONArray getSunfa3(String createTime) {
		// TODO Auto-generated method stub
		if ("".equals(createTime) || null == createTime) {
			createTime = DateTools.getCurrentDate("yyyyMMdd");
		}
		Session session = ContextUtil.getSessionFactory1().openSession();
		List<StockFenqi> list = session.createQuery("from SuanFaModel2 t where t.createTime = ?0")
				.setParameter(0, createTime).list();
		return JSONArray.fromObject(list);
	}

	@Override
	public JSONArray getSuanFa2select(Object object) {
		// TODO Auto-generated method stub
		Session session = ContextUtil.getSessionFactory1().openSession();
		List<String> list = session.createSQLQuery("select DISTINCT(create_time) from suan_fa_model2 t").list();
		return JSONArray.fromObject(list);
	}

}
